import {Controller, Get, Inject, Query, Req, UseGuards} from "@nestjs/common";
import {getRepository} from 'typeorm'
import axios from 'axios'
import {UserEntity} from "./user/user.entity";
import { JwtService } from "@nestjs/jwt";
import {AuthService} from "./auth/auth.service";
import { JwtAuthGuard } from "./auth/guards/jwt-auth.guard";


@Controller('callback')
export class Oauth2Controller {

  @Inject()
  private readonly authService: AuthService;

  @Get('github')
  async github(@Query() query) {
    const code = query.code;

    const clientID = '24c3f9c7a4711785aea4';
    const clientSecret = '4d269ad973baabc58d6476a7215789d3ae6467b9';
    const requestToken = query.code;

    const tokenResponse = await axios({
      method: 'post',
      url: 'https://github.com/login/oauth/access_token?' +
        `client_id=${clientID}&` +
        `client_secret=${clientSecret}&` +
        `code=${requestToken}`,
      headers: {
        accept: 'application/json'
      },
    });


    const result = await axios({
      method: 'get',
      url: `https://api.github.com/user`,
      headers: {
        accept: 'application/json',
        Authorization: `token ${tokenResponse.data.access_token}`
      },
    });


    const user = result.data;
    const member = await getRepository(UserEntity).findOne({username: user.login})
    if (!member) {
      const addMember = {
        avatar: user.avatar_url,
        username: user.login,
        email: user.email,
        password: ""+user.id,
        cliToken: '11111',
        salt: ""+user.id,
      }
      const addUser = await getRepository(UserEntity).insert(addMember);
      const accessToken = await this.authService.sign({
        addUser
      })
      return {
        accessToken,
        user: addUser
      }
    } else {
      const accessToken = await this.authService.sign({id: member.id})
      return {
        accessToken,
        user: member
      }
    }
  }

  @UseGuards(JwtAuthGuard)
  @Get('verify')
  async verify(@Req() req) {
    return req.user;
  }

  @Get("cli/token")
  async cliToken(@Query() query) {
    if (!query.token) {
      throw new Error('no token')
    }

    const user = await getRepository(UserEntity).findOne({cliToken: query.token})
    if (!user) {
      return 'error';
    }
    const accessToken = await this.authService.sign({id: user.id})
    return {
      accessToken,
      user: user
    }
  }
}
